package com.beiyou.orderingsystemonweb.system.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.beiyou.orderingsystemonweb.system.dao.LoginDao;
import com.beiyou.orderingsystemonweb.system.domain.Login;
import com.beiyou.orderingsystemonweb.system.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class LoginService {
    @Autowired
    LoginDao loginDao;
    public String queryIdByAcc(String acc){
        return loginDao.queryIdByAcc(acc);
    }
    public Result<Login> queryLoginByAcc(String acc, String pwd){
        //先是cookie登录
        Login login = loginDao.queryUserByAcc(acc, pwd);
        Result<Login> loginResult = new Result<>();
        if (login!=null){
            loginResult.setT(login);
            loginResult.setType(2);
            return loginResult;
        }
        else{
            String id = queryIdByAcc(acc);
            if (id!=null){
                //用户账号密码登录
                login = loginDao.queryUserByAcc(acc,DigestUtil.md5Hex(id+pwd));
                if (login != null) {
                    loginResult.setT(login);
                    loginResult.setType(1);
                    return loginResult;
                }
                else{
                    loginResult.setType(-1);
                    loginResult.setMsg("密码输入错误");
                    return loginResult;
                }
            }
            else{
                loginResult.setType(-2);
                loginResult.setMsg("账号输入错误");
                return new Result<>();
            }
        }
    }

    //封装的ajax请求,有意义的字段名是acc，实际意义是id
    public Map queryAcc(String acc){
        Map map = new HashMap();
        map.put("acc",queryIdByAcc(acc));
        return map;
    }
}
